//
//  MTMineViewController.m
//  ebook
//
//  Created by 吴超飞 on 16/1/14.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "MTMineViewController.h"
#import "UIImage+Color.h"
#import "MTLoginViewController.h"
#import "MTRegisterViewController.h"
#import "EbookNetRequest.h"
#import "MBProgressHUD.h"
#import "SettingViewController.h"
#import "HeadView.h"
#import "FeedbackViewController.h"
#import "ToastView.h"
#import "UIImageView+WebCache.h"
#import "MTRate.h"
#import "MISAlertController.h"
#import "VipViewController.h"
#import "MTNavigationController.h"

#define TOPIMGHEIGHT 250
#define kUnreadLabelTag 66

@interface MTMineViewController ()<UITableViewDataSource, UITableViewDelegate, HeadViewDelegate, LoginDelegate,MTRateDelegate>{
    BOOL hasUsedFeedback;//是否已经使用过意见反馈
    BOOL hasClickFeedback;//意见反馈点击，防止多次点击弹出多个页面
}

@property (nonatomic, retain) UILabel *titleLabel;
@property (nonatomic, assign) BOOL isCanChangeUser;//是否能切换用户

@property (nonatomic, retain) NSDictionary *shareDic;

@property (nonatomic, retain) HeadView *headView;

@property (nonatomic, retain) UIView *shareView;
@property (nonatomic, strong) NSString *unreadStr;//反馈未读数
@property (nonatomic, strong) UILabel *unreadLabel;

@end

@implementation MTMineViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.title = @"我的账号";
    self.tabBarItem.title = @"我的";
    
    id data = [[NSUserDefaults standardUserDefaults] objectForKey:KBookCityData];
    NSDictionary *dic= [NSKeyedUnarchiver unarchiveObjectWithData:data];
    _shareDic = [[NSDictionary alloc] initWithDictionary:dic[@"data"][@"shareinfo"]];
    
    CGRect frame = self.view.bounds;
    float offset11 = 44;//IOS11中顶上会有白边，并且下拉会闪动
    frame.origin.y = -offset11;
    if(MTScreenH==480)frame.size.height -= 49;//4s屏幕尺寸问题，视图大小需单独计算
    self.mainTableView = [[UITableView alloc] initWithFrame:frame style:UITableViewStyleGrouped];
    self.mainTableView.delegate = self;
    self.mainTableView.dataSource = self;
    self.mainTableView.backgroundColor = MTConfigColor(@"MTMine_tableviewBg_Color");
    self.mainTableView.separatorInset = UIEdgeInsetsMake(0, 15, 0, 0);
    [self.view addSubview:self.mainTableView];
    
    self.headView.frame = CGRectMake(0, 0, MTScreenW, TOPIMGHEIGHT+offset11);
    self.mainTableView.tableHeaderView = self.headView;
    
    self.edgesForExtendedLayout=UIRectEdgeNone;
    self.extendedLayoutIncludesOpaqueBars=NO;
    if(iOS11){
        if ([self.mainTableView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
            self.mainTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            
            self.mainTableView.estimatedRowHeight = 0;
            self.mainTableView.estimatedSectionHeaderHeight = 0;
            self.mainTableView.estimatedSectionFooterHeight = 0;
        }
    }
    self.automaticallyAdjustsScrollViewInsets=NO;

    UIButton *leftBtn = [[UIButton alloc] initWithFrame:CGRectMake(2, 20+(iPhoneX?22:0), 50, 44)];
    [leftBtn setImage:[UIImage imageNamed:@"back_arrow"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(leftBtnClick:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:leftBtn];
}

-(void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
}

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    
    self.isCanChangeUser = [[NSUserDefaults standardUserDefaults] boolForKey:kIsLogin]&&![[NSUserDefaults standardUserDefaults] boolForKey:kIsGuest];//非游客登陆状态下才可以切换用户
    [_headView updateView];
    [self.mainTableView reloadData];
//    if([self isOpenBaichuan])[self getUnreadCount];
}

//是否开启百川的用户反馈
-(BOOL)isOpenBaichuan{
    
    NSDictionary *dict = kBookCityDataDict;
    int openbc = [dict[@"openbc"] intValue];
    return openbc == 1;
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

-(void)leftBtnClick:(UIButton *)btn{
    
    self.tabBarController.selectedIndex = 1;
}

-(HeadView *)headView{
    
    if (!_headView) {
        _headView = [[[NSBundle mainBundle] loadNibNamed:@"HeadView" owner:nil options:nil] lastObject];
        _headView.delegate = self;
    }
    return _headView;
}

#pragma mark- scroll delegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    self.headView.offsetY = scrollView.contentOffset.y;
}

#pragma mark - UITableView Delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 44;
}

#pragma mark - UITableView Datasources
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return _isCanChangeUser ? 3:2;//只有登录了，才有退出登录的菜单
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return section==0 ? 10:0.000001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)sectionIndex {
    
    NSInteger count = 1;
    switch (sectionIndex) {
            
        case 0:
            count = 3;
            break;
        case 1:
            count = kIsEnabledVip?2:1;
            break;
        default:
            break;
    }
    return count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *identifier = @"myIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.selectionStyle = UITableViewCellSelectionStyleBlue;
    }
    NSString *text = @"";
    NSString *iconName = @"";
    switch (indexPath.section) {
        case 0://section 1
            switch (indexPath.row) {
                case 0:
                    text = @"给我评分";
                    iconName = @"score_icon";//       about_icon
                    break;
                case 1:
                    text = @"我要吐槽";
                    iconName = @"feedback_icon";
                    break;
                case 2:
                    text = @"推荐给小伙伴";
                    iconName = @"share_icon";
                    _shareView = cell;
                    break;
            }
            break;
        case 1://section 2
            switch (indexPath.row) {
                case 0:
                    text = @"设置";
                    iconName = @"set_icon";
                    break;
                case 1:
                    text = @"去广告";
                    iconName = @"vip_icon";
                    break;
            }
            break;
        case 2://section 3
            switch (indexPath.row) {
                case 0:
                    text = @"切换账号";
                    iconName = @"account_icon";
                    break;
            }
            break;
            
        default:
            break;
    }
    
    cell.textLabel.text = text;
    cell.imageView.image = [UIImage imageNamed:iconName];
    for (UIView *sub in cell.contentView.subviews) {
        if (sub.tag==kUnreadLabelTag && [sub isKindOfClass:[UILabel class]]) {
            [sub removeFromSuperview];
        }
    }
    
    double interval = [[NSDate date] timeIntervalSince1970]-[[NSUserDefaults standardUserDefaults] doubleForKey:kReadBaichuanMsgTime];
    if (_unreadStr&&(interval>(hasUsedFeedback?5*60:10*60))) {//使用过意见反馈五分钟获取，否则十分钟获取
        if (indexPath.section==0&&indexPath.row==1) {
            self.unreadLabel.text = _unreadStr;
            [cell.contentView addSubview:self.unreadLabel];
        }
    }else{
        if (indexPath.section==0&&indexPath.row==1) {
            [self.unreadLabel removeFromSuperview];
        }
    }
    
    if(indexPath.row==1&&indexPath.section==1){
        NSInteger time = [[NSUserDefaults standardUserDefaults]integerForKey:kVipOverTime];
        cell.detailTextLabel.text = time==0?@"":[NSString stringWithFormat:@"%@到期",[self timestampSwitchDate:time]];
    }
    
    return cell;
}
-(UILabel *)unreadLabel{
    
    if (!_unreadLabel) {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(MTScreenW-60, (44-24)/2, 24, 24)];
        label.font= [UIFont systemFontOfSize:15.0f];
        label.textAlignment = NSTextAlignmentCenter;
        label.backgroundColor = [UIColor redColor];
        label.textColor = [UIColor whiteColor];
        label.layer.cornerRadius = 24/2;
        label.clipsToBounds = YES;
        label.tag = kUnreadLabelTag;
        _unreadLabel = label;
    }
    return _unreadLabel;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    switch (indexPath.section) {
        case 0://section 1
            switch (indexPath.row) {
                case 0://给我评分
                {
                    int openrate = [[[NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] objectForKey:KBookCityData]] objectForKey:@"openrate"] intValue];//待评论的appid
                    if(openrate>0){
                        [[MTRate shareInstance] rate];
                        [MTRate shareInstance].delegate = self;
                    }else if(openrate<=0){
                        NSString *str = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/id%@?action=write-review", kAppidInAppstore];//[NSString stringWithFormat: @"itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=%@", kAppidInAppstore];
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
                    }
                }
                    break;
                case 1://意见反馈
                {
                    [self mtRateFeedBack:nil];
                }
                    break;
                case 2:
                {
                    UIPasteboard*pasteboard = [UIPasteboard generalPasteboard];
                    pasteboard.string = [NSString stringWithFormat:@"%@：%@",_shareDic[@"intro"], _shareDic[@"url"]];
                    [self showMsg:@"分享地址已经复制到剪切板，快去粘贴分享给好友吧" title:@"分享给好友" okName:@"我知道了"];
                    /*
                    UIImageView *imageV = [[UIImageView alloc] init];
                    NSString *text = [NSString stringWithFormat:@"%@\n%@", _shareDic[@"intro"], _shareDic[@"url"]];
                    UIView *shareView = nil;
                    if (isIpad) {
                        shareView = _shareView;
                    }
                    if (!_shareDic[@"imageurl"]) {
                        imageV.image = [UIImage imageNamed:@"share"];
                        [super sharewithview:shareView text:text dic:_shareDic imagesArray:@[imageV.image]];
                    } else {
                        [imageV sd_setImageWithURL:[NSURL URLWithString:_shareDic[@"imgurl"]] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                            [super sharewithview:shareView text:text dic:_shareDic imagesArray:@[image?image:[UIImage imageNamed:@"share"]]];
                        }];
                    }*/
                }
                    break;
            }
            break;
        case 1://section 2
            switch (indexPath.row) {
                case 0://设置
                {
                    SettingViewController *settingVc = [[SettingViewController alloc]init];
                    [self.navigationController pushViewController:settingVc animated:YES];
                }
                    break;
                case 1://VIP
                {
                    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                    VipViewController *vipVc = [storyboard instantiateViewControllerWithIdentifier:@"VipViewController"];
                    [self.navigationController pushViewController:vipVc animated:YES];
                }
                    break;
            }
            break;
        case 2://section 3
            switch (indexPath.row) {
                case 0://切换账号
                {
                    [self infoAndLogin];
                }
                    break;
            }
            break;
            
        default:
            break;
    }
}

-(void)showMsg:(NSString *)msg title:(NSString *)title okName:(NSString *)ok{
    
    UIAlertController *alertVc  = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:ok style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {}];
    [alertVc addAction:sureAction];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertVc animated:YES completion:nil];
}

//提示并登录
-(void)infoAndLogin{
    MISAlertController *alertController = [MISAlertController alertControllerWithTitle:@"提示" message:@"切换帐号将重置您的书架，是否继续？" preferredStyle:UIAlertControllerStyleAlert];
    MISAlertAction *cancelAction = [MISAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(MISAlertAction *action) {
    }];
    
    MISAlertAction *okAction = [MISAlertAction actionWithTitle:@"继续切换" style:UIAlertActionStyleDefault handler:^(MISAlertAction *action) {
        [self login];
    }];
    
    [alertController addAction:okAction];
    [alertController addAction:cancelAction];
    [alertController showInViewController:self animated:YES];
}

-(void)login{
    
    MTLoginViewController *loginVc = [[MTLoginViewController alloc] init];
    loginVc.delegate = self;
    if (self.isCanChangeUser) {//已登陆，切换用户，不显示用户名，title显示：切换用户
        loginVc.isClickSwitchUser = YES;
        loginVc.userName = @"";
    }
    [self.navigationController pushViewController:loginVc animated:YES];
}

#pragma mark - HeadViewDelegate
-(void)headView:(HeadView *)view loginBtnClick:(BOOL)login{
    
    [self infoAndLogin];
}

-(void)headView:(HeadView *)view blindGuestBtnClick:(UIButton *)btn{
    
    [self infoAndLogin];
}

-(void)headView:(HeadView *)view leftBtnClick:(UIButton *)btn{
    
    self.tabBarController.selectedIndex = 1;
}

-(void)headView:(HeadView *)view rightBtnClick:(UIButton *)btn{
    MTLog(@"message button click");
}

#pragma mark - LoginDelegate
-(void)loginSuccess{
    
    [self.headView updateView];
    [self.mainTableView reloadData];
}

-(void)loginCancel{
    
}


#pragma mark - MTRateDelegate
- (void)mtRateFeedBack:(MTRate *)rate {
   
//    if([self isOpenBaichuan])
//        [self feedBack];
//    else
    {
        FeedbackViewController *feedVc = [[FeedbackViewController alloc] init];
        [self.navigationController pushViewController:feedVc animated:YES];
    }
}
/*
#pragma mark getter
- (YWFeedbackKit *)feedbackKit {
    if (!_feedbackKit) {
        _feedbackKit = [[YWFeedbackKit alloc] initWithAppKey:kBaichuanAppKey];
    }
    return _feedbackKit;
}

- (void)feedBack {
    
    if(hasClickFeedback)return;
    hasClickFeedback = YES;
    hasUsedFeedback = YES;
    NSString *userName = [[NSUserDefaults standardUserDefaults] objectForKey:kUserName];
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSString *displayName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"];
    self.feedbackKit.extInfo = @{@"loginTime":[[NSDate date] description],
                                 @"visitPath":@"意见反馈",
                                 @"userid":userName,
                                 @"version":version,
                                 @"displayName":displayName};
   
    __weak typeof(self) weakSelf = self;
    [self.feedbackKit makeFeedbackViewControllerWithCompletionBlock:^(YWFeedbackViewController *viewController, NSError *error) {
        if (viewController != nil) {
            
            [weakSelf.navigationController pushViewController:viewController animated:YES];
            hasClickFeedback = NO;
            [viewController setCloseBlock:^(UIViewController *aParentController){
                [aParentController.navigationController popViewControllerAnimated:YES];
                _unreadStr = nil;
                [[NSUserDefaults standardUserDefaults] setDouble:[[NSDate date]timeIntervalSince1970] forKey:kReadBaichuanMsgTime];
                [[NSUserDefaults standardUserDefaults]synchronize];
                [self reloadFeedBack];
            }];
        } else {
            MTLog(@"接口调用失败，请保持网络通畅！");
        }
    }];
}

- (void)getUnreadCount {
    [self.feedbackKit getUnreadCountWithCompletionBlock:^(NSInteger unreadCount, NSError *error) {
        if (error == nil) {
            MTLog(@"未读消息个数%ld", unreadCount);
            _unreadStr = nil;
            if (unreadCount>0 && unreadCount<10) {
                _unreadStr = [NSString stringWithFormat:@"%ld", unreadCount];
            } else if (unreadCount>9) {
                _unreadStr = @"9+";
            }
        } else {
            MTLog(@"未读反馈信息个数接口调用失败，请保持网络通畅！");
            _unreadStr = nil;
        }
        [self reloadFeedBack];
    }];
}*/

-(void)reloadFeedBack{
    [self.mainTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
}

@end
